<template>
	<view class="layout">		
		<view class="picGroup">
			<view class="box add" @click="selectPic" v-if="pictures.length==0">+</view>
			<view class="box" v-for="item,index in pictures" :key="index">
				<image :src="item.temp" mode="aspectFill"></image>
				<view class="close" @click="handleClose">×</view>
				<view class="mask" v-if="item.status == 1">{{item.progress}}%</view>
			</view>
		</view>
		
	</view>
</template>

<script setup>
import { ref } from 'vue';
import dayjs from "dayjs"
const pictures = ref([]);
const uploadFileObj = uniCloud.importObject("uploadFileObj");
//{temp:"",fileID:"",url:"",status:2,progress:0}
const selectPic = async()=>{
	let file = await uni.chooseImage({
		count:1		
	})		
	pictures.value = file.tempFilePaths.map(item=>({temp:item,status:0,progress:0}))
	
	let filename = dayjs().format("YYYYMMDD")+"/"+Date.now()+".jpg";
	pictures.value[0].status = 1;
	let cloud = await uniCloud.uploadFile({
		filePath:pictures.value[0].temp,
		cloudPath:filename,
		onUploadProgress:event=>{			
			pictures.value[0].progress = Math.round(
				(event.loaded * 100) / event.total
			);
		}
	})
	pictures.value[0].status = 2;
	console.log(cloud.fileID);
	let path = cloudToHttps(cloud.fileID);
	pictures.value[0].fileID = cloud.fileID;
	pictures.value[0].url = path;
	console.log(pictures.value);
	
}


const handleClose = ()=>{
	uploadFileObj.remove([pictures.value[0].fileID])
	.then(res=>{
		console.log(res);
	})
	pictures.value = [];
}


const cloudToHttps = (str)=>{
	return str.replace("cloud://", "https://")
	.replace(str.split("/")[2], str.split("/")[2] + ".normal.cloudstatic.cn");	
}

</script>

<style lang="scss" scoped>
.layout{
	padding:30rpx;
	.picGroup{
		display: grid;
		grid-template-columns:repeat(3,1fr);
		gap:20rpx;
		.box{
			width: 100%;
			aspect-ratio: 1 / 1;
			position: relative;
			image{
				width: 100%;
				height: 100%;
				display: block;
			}
			.close{
				position: absolute;
				top:10rpx;
				right:10rpx;
				width: 60rpx;
				height: 60rpx;
				background: rgba(0,0,0,0.6);
				color:#fff;
				border-radius: 50%;
				border:1px solid #fff;
				display: flex;
				align-items: center;
				justify-content: center;				
			}
			.mask{
				position: absolute;
				top:0;
				left:0;
				width: 100%;
				height:100%;
				background: rgba(0,0,0,0.6);
				color:#fff;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
		.add{
			background: #eee;
			font-size: 90rpx;
			color:#333;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
	
}
</style>
